import Vue from "vue";
import Vuex from "vuex";

import axios from 'axios'

Vue.use(Vuex)

const state = {
    isFirst: true,
    isLoading: false,
    isError: '',
    cards: []
}

const mutations = {
    GETUSERLIST(state, filteUserList) {
        state.isLoading = false
        state.cards = filteUserList
    },
    REQBEFORE(state) {
        state.isFirst = false
        state.isLoading = true
    },
    RESED(state,error){
        state.isLoading = false
        state.isError = '错误：' + error
    }
}

const actions = {
    async getUserList({ commit }, keyword) {
        try {
            commit('REQBEFORE')
            const { data: { items } } = await axios({
                url: 'https://api.github.com/search/users',
                params: {
                    q: keyword
                }
            })
            const filteUserList = items.map(item => ({
                id: item.id,
                login: item.login,
                url: item.url,
                avatar_url: item.avatar_url
            }))
            commit('GETUSERLIST', filteUserList)
        } catch (error) {
            commit('RESED',error.message)
        }
    }
}

const getters = {

}

export default new Vuex.Store({
    state,
    mutations,
    actions,
    getters,
})